<template>
  <div class="article-list">
    <!-- List 组件通过 loading 和 finished 两个变量控制加载状态，当组件滚动到底部时，会触发 load 事件并将 loading 设置成 true。此时可以发起异步操作并更新数据，数据更新完毕后，将 loading 设置成 false 即可。若数据已全部加载完毕，则直接将 finished 设置成 true 即可。 -->
    
    <!-- success-duration="2000"  刷新成功提示展示时长属性
    添加成功提示属性 success-text -->
    <van-pull-refresh
      v-model="refreshing"
      :success-text="refreshSuccessText"
      :success-duration="1000" 
      @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad">
        <article-item v-for="(article, index) in list" :key="index + '-only'" :article="article"></article-item>
        <van-cell
          v-for="(item, index) in list"
          :key="index"
          :title="item.title" />
      </van-list>
    </van-pull-refresh>

  </div>
</template>

<script>
import { getArticles } from "@/api/article.js";
import ArticleItem from '@/components/article-item'
export default {
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: null,
      refreshing: false,
      refreshSuccessText:'刷新成功'
    };
  },
  components: {
    ArticleItem
  },
  props: {
    homelist: {
      type: Object,
      required: true,
    },
  },
  methods: {
    // 加载中，没有更多
    async onLoad () {
      try {
        const { data } = await getArticles({
          channel_id: this.homelist.id,
          timestamp: Date.now() || this.timestamp,
        });
        // 2. 把数据添加到 list 数组中
        const { results } = data.data
        this.list.push(...results)
        this.loading = false;
        if (results.length) {
          this.timestamp = data.data.pre_timestamp;
        } else {
          this.finished = true
        }
      } catch (err) {
        this.$toast.fail("获取数据失败", err)
      }
    },
    // 下拉刷新 下拉刷新 下拉刷新
    async onRefresh () {
      try {
        const { data } = await getArticles({
          channel_id: this.homelist.id,
          timestamp: Date.now(),
        })
        const { results } = data.data
        this.list.unshift(...results)
        this.refreshSuccessText = `刷新成功，更新了${results.length}条数据`
        this.refreshing = false;
      } catch (err) {
        this.$toast.fail("获取数据失败", err)
        this.refreshSuccessText = '刷新失败'
        this.refreshing = false
      }
      
    },
  },
};
</script>

<style scoped lang="less">
.article-list {
  height: 79vh;
  overflow-y: auto;
}
</style>